package com.estasenposse.tdam.ui.adapter;

import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;

public class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
	private ImageView bmImage;
	private ProgressBar pgLoading;
	private Context context;

	public ImageDownloader(ImageView bmImage, ProgressBar loading,
			Context context) {
		this.bmImage = bmImage;
		this.pgLoading = loading;
		if (context != null) {
			this.context = context;
		}

	}

	@Override
	protected void onPreExecute() {
		pgLoading.setVisibility(View.VISIBLE);
	}

	protected Bitmap doInBackground(String... urls) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();

		Bitmap mIcon11 = null;

		if (networkInfo != null && networkInfo.isConnected()) {
			String urldisplay = urls[0];

			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				e.printStackTrace();
			}			
		}
		return mIcon11;
	}

	@Override
	protected void onPostExecute(Bitmap result) {
		bmImage.setImageBitmap(result);
		pgLoading.setVisibility(View.GONE);
		bmImage.setVisibility(View.VISIBLE);
	}
}